"use client"

import { useState, useRef, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { ArrowLeft, ImageIcon, Video, Music, MapPin, X, Globe, Lock, Users } from "lucide-react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { toast } from "@/components/ui/use-toast"
import { cn } from "@/lib/utils"
import type { ShareableResource } from "@/components/more-options-menu"
import { LocationPicker } from "@/components/resource-picker/location-picker"

interface Location {
    name: string
    address: string
    distance: number
    city?: string
}

export default function SharePage() {
    const [content, setContent] = useState("")
    const [visibility, setVisibility] = useState("public")
    const [showLocationPicker, setShowLocationPicker] = useState(false)
    const [selectedLocation, setSelectedLocation] = useState<Location | null>(null)
    const [sharedResource, setSharedResource] = useState<ShareableResource | null>(null)
    const [isLoading, setIsLoading] = useState(false)
    const [isSubmitting, setIsSubmitting] = useState(false)
    const fileInputRef = useRef<HTMLInputElement>(null)
    const router = useRouter()

    // 获取分享的资源信息
    useEffect(() => {
        setIsLoading(true)

        try {
            const resourceJson = sessionStorage.getItem("shareResource")
            if (resourceJson) {
                const resource = JSON.parse(resourceJson)
                setSharedResource(resource)
            } else {
                // 如果没有分享的资源，显示提示但不自动跳转
                toast({
                    title: "未找到分享内容",
                    description: "请从音乐、专辑或其他内容页面发起分享"
                })
            }
        } catch (error) {
            console.error("Failed to parse shared resource:", error)
            toast({
                title: "解析分享内容失败",
                description: "请重新尝试分享"
            })
        } finally {
            setIsLoading(false)
        }
    }, [])

    const handleSubmit = async () => {
        if (!sharedResource) {
            toast({
                title: "分享失败",
                description: "未找到分享内容"
            })
            return
        }

        setIsSubmitting(true)

        try {
            // 创建一个FormData对象来处理提交
            const formData = new FormData()
            formData.append("content", content)
            formData.append("visibility", visibility)
            formData.append("resourceType", sharedResource.type)
            formData.append("resourceId", sharedResource.id.toString())

            if (selectedLocation) {
                formData.append("locationName", selectedLocation.name)
                formData.append("locationAddress", selectedLocation.address)
                if (selectedLocation.city) {
                    formData.append("locationCity", selectedLocation.city)
                }
            }

            // 这里应该调用API来保存分享
            console.log("分享内容:", formData)

            // 模拟API调用
            await new Promise((resolve) => setTimeout(resolve, 1000))

            // 清除分享的资源信息
            sessionStorage.removeItem("shareResource")

            toast({
                title: "分享成功",
                description: "您的分享已经成功发布",
            })

            // 发布成功后再跳转到社区页面
            router.push("/community")
        } catch (error) {
            console.error("Failed to share:", error)
            toast({
                title: "分享失败",
                description: "请稍后重试"
            })
        } finally {
            setIsSubmitting(false)
        }
    }

    const handleLocationSelect = (location: Location | null) => {
        setSelectedLocation(location)
        setShowLocationPicker(false)
    }

    const removeSharedResource = () => {
        setSharedResource(null)
        // 不自动跳转，而是让用户手动返回
    }

    const handleBack = () => {
        // 返回上一页，不清除资源信息，以便用户可以再次尝试
        router.back()
    }

    if (isLoading) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <div className="text-center">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
                    <p className="text-muted-foreground">加载中...</p>
                </div>
            </div>
        )
    }

    return (
        <div className="min-h-screen bg-background">
            <div className="fixed top-0 left-0 right-0 bg-background border-b p-4 flex items-center justify-between z-10">
                <Button variant="ghost" size="icon" onClick={handleBack}>
                    <ArrowLeft className="h-6 w-6" />
                </Button>
                <h1 className="text-lg font-semibold">分享到社区</h1>
                <div className="w-10"></div> {/* 占位，保持标题居中 */}
            </div>

            <div className="pt-16 px-4 pb-20 max-w-2xl mx-auto">
                <Textarea
                    placeholder="分享你的想法..."
                    value={content}
                    onChange={(e) => setContent(e.target.value)}
                    className="w-full min-h-[200px] text-lg border-none resize-none focus-visible:ring-0"
                    maxLength={1000}
                    autoFocus
                />

                {/* 分享资源预览 */}
                {sharedResource ? (
                    <div className="mt-4 relative">
                        <div className="relative rounded-lg overflow-hidden bg-muted">
                            <div className="flex items-center space-x-4 p-4">
                                <img
                                    src={sharedResource.cover || "/placeholder.svg?height=64&width=64"}
                                    alt={sharedResource.title}
                                    className="w-16 h-16 rounded object-cover"
                                />
                                <div>
                                    <h4 className="font-medium">{sharedResource.title}</h4>
                                    {sharedResource.artist && <p className="text-sm text-muted-foreground">{sharedResource.artist}</p>}
                                    <p className="text-xs text-muted-foreground mt-1">
                                        {sharedResource.type === "song" && "单曲"}
                                        {sharedResource.type === "album" && "专辑"}
                                        {sharedResource.type === "playlist" && "歌单"}
                                        {sharedResource.type === "mv" && "MV"}
                                        {sharedResource.type === "artist" && "歌手"}
                                    </p>
                                </div>
                            </div>
                            <Button variant="secondary" size="icon" className="absolute top-2 right-2" onClick={removeSharedResource}>
                                <X className="h-4 w-4" />
                            </Button>
                        </div>
                    </div>
                ) : (
                    <div className="mt-4 p-4 border border-dashed rounded-lg text-center text-muted-foreground">
                        未找到分享内容，请返回并重新尝试分享
                    </div>
                )}

                <div className="flex justify-between mt-4">
                    <div className="flex space-x-2">
                        <input type="file" accept="image/*" className="hidden" ref={fileInputRef} />
                        <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => setShowLocationPicker(true)}
                            className={cn(selectedLocation && "text-primary")}
                        >
                            <MapPin className="h-5 w-5" />
                        </Button>
                        <Button variant="ghost" size="icon">
                            <ImageIcon className="h-5 w-5" />
                        </Button>
                        <Button variant="ghost" size="icon">
                            <Video className="h-5 w-5" />
                        </Button>
                        <Button variant="ghost" size="icon">
                            <Music className="h-5 w-5" />
                        </Button>
                    </div>
                    <div className="text-sm text-muted-foreground">{content.length}/1000</div>
                </div>

                {selectedLocation && (
                    <div className="flex items-center gap-2 mt-4 text-[#00b578]">
                        <MapPin className="h-5 w-5" />
                        <span className="text-sm">
              {selectedLocation.city ? `${selectedLocation.city}·${selectedLocation.name}` : selectedLocation.name}
            </span>
                    </div>
                )}

                <div className="mt-6 space-y-4">
                    <div className="flex items-center space-x-2">
                        <span className="text-sm font-medium">可见范围</span>
                        <Select value={visibility} onValueChange={setVisibility}>
                            <SelectTrigger className="w-[180px]">
                                <SelectValue placeholder="选择可见范围" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="public">
                                    <div className="flex items-center">
                                        <Globe className="mr-2 h-4 w-4" />
                                        <span>公开</span>
                                    </div>
                                </SelectItem>
                                <SelectItem value="friends">
                                    <div className="flex items-center">
                                        <Users className="mr-2 h-4 w-4" />
                                        <span>仅好友可见</span>
                                    </div>
                                </SelectItem>
                                <SelectItem value="private">
                                    <div className="flex items-center">
                                        <Lock className="mr-2 h-4 w-4" />
                                        <span>仅自己可见</span>
                                    </div>
                                </SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                </div>

                <div className="mt-8">
                    <Button onClick={handleSubmit} className="w-full" disabled={isSubmitting || !sharedResource}>
                        {isSubmitting ? "发布中..." : "发表"}
                    </Button>
                </div>
            </div>

            {/* 位置选择器 */}
            <LocationPicker
                open={showLocationPicker}
                onOpenChange={setShowLocationPicker}
                onSelect={handleLocationSelect}
                currentLocation={selectedLocation}
            />
        </div>
    )
}

